<?php

namespace app\admin\controller;

use app\admin\middleware\Article as MiddlewareArticle;
use app\admin\model\Article as ModelArticle;
use app\admin\model\Category;
use app\admin\model\CategoryAdmin;
use app\admin\validate\Article as ValidateArticle;
use app\common\LogService;
use app\common\Notification as CommonNotification;
use app\Request;
use think\exception\ValidateException;
use think\facade\Db;

class Article extends Base
{
    protected $middleware = [MiddlewareArticle::class => ['only' => ['doAdd']]];
    public function index()
    {
        Category::$is_all = 1;
        $cate = Category::list();
        $artNoExamine = ModelArticle::where(['status' => 0])->count();
        return view('index', ['cate' => $cate, 'art' => $artNoExamine]);
    }
    public function list()
    {
        $limit = input('limit');
        $id = input('id');
        $title = input('title');
        $user_id = input('user_id');
        $cate_id = input('cate_id');
        $list = ModelArticle::with(['category' => function ($query) {
            $query->field('id,cate_name');
        }]);
        if (!empty($id)) {
            $list->where(['id' => $id]);
        }
        if (!empty($title)) {
            $list->where('title', 'like', "%$title%");
        }
        if (!empty($user_id)) {
            $list->where(['user_id' => $user_id]);
        }

        if (!empty($cate_id)) {
            $list->where(['cate_id' => $cate_id]);
        }
        if ($this->role == 2) {
            $cate_id = CategoryAdmin::getChildCateId($this->uid);
            $list->where('cate_id', 'in', $cate_id);
        }
        $list = $list->order('status asc,id desc')->paginate($limit);
        return success($list);
    }
    public function read($id)
    {
        $data = ModelArticle::with(['category' => function ($query) {
            $query->field('id,cate_name');
        }, 'userInfo' => function ($query) {
            $query->field('id,nickname,avator,signature');
        }])->where(['id' => $id])->find();
        if (!$data) return view('error/404');
        // $data['images'] = explode(',', checkImg($data['images']));
        LogService::record(
            name: '查看文章',
            user_id: $this->uid,
            user_type: 2,
            target_id: $id
        );
        return view('read', ['data' => $data]);
    }
    public function add()
    {
        Category::$is_all = 1;
        $cate = Category::list();
        return view('add', ['cate' => $cate]);
    }
    public function doAdd()
    {
        $param = input();
        $cate_id = CategoryAdmin::getChildCateId($this->uid);
        if (in_array($param['cate_id'], $cate_id) || $this->role ==  0) {
            $param['status'] = 1;
        }
        $param['user_id'] = $this->uid;
        $param['content'] = remove_xss($param['content']);
        LogService::record(
            user_id: $this->uid,
            name: '添加文章',
            user_type: $this->role == 0 ? 2 : 3
        );
        $res = ModelArticle::create($param);
        if ($res)   return success();
        return error();
    }
    public function edit($id)
    {
        $art = ModelArticle::verifyCategoryAdmin($id);
        if (!$art) {
            return view('error/error', ['msg' => "权限不足"]);
        }
        Category::$is_all = 1;
        $cate = Category::list();
        return view('edit', ['data' => $art, 'cate' => $cate]);
    }
    public function doEdit()
    {
        $param = input('post.');
        try {
            // 特殊处理字段 reviewer_id ,cate_id , type ,images ,score
            validate(ValidateArticle::class)->scene('edit')->check($param);
            $target_id = $param['id'];
            $recordLog = function ($status, $message = '') use ($target_id) {
                LogService::record(
                    name: '编辑文章',
                    user_id: $this->uid,
                    target_id: $target_id,
                    status: $status,
                    content: $message == '' ? [] : ['reason' => $message],
                    user_type: $this->role == 0 ? 2 : 3


                );
            };
            $art = ModelArticle::where(['id' => $param['id']])->find();
            if (!$art) return error('文章不存在');
            $cate_id = CategoryAdmin::getChildCateId($this->uid);
            if (!in_array($art['cate_id'], $cate_id) && $this->role != 0) {
                return view('error/error', ['msg' => "权限不足"]);
            }
            // 最后修改文章的管理员ID
            $param['reviewer_id'] = $this->uid;
            $title = $art['title'];
            if ($art['status'] != $param['status'] && $param['status'] == 1) {
                $content = "你发布的文章《 $title 》已通过审核";
                CommonNotification::send($art['user_id'], $content, 2, $art['id']);
            }
            if ($art['status'] != $param['status'] && $param['status'] == 2) {
                $content = "你发布的文章《 $title 》已被管理员锁定，请友好发帖";
                CommonNotification::send($art['user_id'], $content, 2, $art['id']);
            }
            $hasCate = Db::name('category')->where(['id' => $param['cate_id']])->find();
            if (!$hasCate) {
                $recordLog(0, '分类不存在');
                return error('分类不存在');
            }
            if ($hasCate['pid'] == 0) {
                $recordLog(0, '分类必须为二级分类');
                return error('分类必须为二级分类');
            }
            if (@$param['images'] != '') {
                $param['images'] = checkImg($param['images']);
            }
            if (@$param['type'] != '') {
                if ($param['type'] == 2 && $param['score'] <= 0) {
                    $recordLog(0, '付费文章积分不能小于0');
                    return error('付费文章积分不能小于0');
                }
            }
            $res = ModelArticle::where(['id' => $param['id']])->update($param);
            if ($res) {
                $recordLog(1);
                return success();
            }
            $recordLog(0, '没有修改任何数据');
            return error();
        } catch (ValidateException $e) {
            return error($e->getError());
        }
    }

    // 一键审核
    public function examineAll()
    {
        $type = input('type', 1);
        $cate_id = CategoryAdmin::getChildCateId($this->uid);
        try {
            if ($type == 1) {
                // 获取所有待审核的文章及其作者信息
                $articles = ModelArticle::where(['status' => 0])->select();
                if ($this->role == 2) {
                    $articles->where('cate_id', 'in', $cate_id);
                }
                foreach ($articles as $article) {
                    // 发送通知给每个作者
                    $content = "你发布的文章《 {$article['title']} 》已通过审核";
                    CommonNotification::send($article['user_id'], $content, 2, $article['id']);
                }
                $target_id =  ModelArticle::where(['status' => 0])->column('id');
                $id = implode(',', $target_id);
                $log_name = '一键审核文章';
                $res = ModelArticle::where(['status' => 0])->update(['status' => 1]);
            } else {
                $id = input('id');
                $ids = explode(',', $id);

                // 获取指定ID的文章及其作者信息
                $articles = ModelArticle::whereIn('id', $ids)->select();
                // 版主只能审核当前权限分类内的文章
                if ($this->role == 2) {
                    $cids = [];
                    foreach ($articles as $k => $v) {
                        if (in_array($v['cate_id'], $cate_id)) {
                            $cids[] = $v;
                        }
                    }
                    $articles = $cids;
                }
                foreach ($articles as $article) {
                    // 发送通知给每个作者
                    $content = "你发布的文章《 {$article['title']} 》已通过审核";
                    CommonNotification::send($article['user_id'], $content, 2, $article['id']);
                }

                $res = ModelArticle::whereIn('id', $ids)->update(['status' => 1]);
                $log_name = '批量审核文章';
            }

            $recordLog = function ($status, $message = '') use ($log_name, $id) {
                LogService::record(
                    user_id: $this->uid,
                    name: $log_name,
                    user_type: $this->role == 0 ? 2 : 3,
                    target_id: $id
                );
            };
            if ($res) {
                $recordLog(1);
                return success();
            }
            $recordLog(0);
            return error();
        } catch (\Exception $e) {
            return error($e->getMessage());
        }
    }
    public function del($id)
    {
        $ids = explode(',', $id);
        if ($this->role != 0) {
            $artData = ModelArticle::where('id', 'in', $ids)->column('cate_id');
            $cateId = CategoryAdmin::getChildCateId($this->uid);
            $delId = [];
            foreach ($artData as $k) {
                if (in_array($k, $cateId)) {
                    $delId[] = $k;
                }
            }
        } else {
            $delId = $ids;
        }
        $res = ModelArticle::destroy($delId);
        LogService::record(
            user_id: $this->uid,
            name: '删除文章',
            target_id: $id,
            user_type: $this->role == 0 ? 2 : 3,
        );
        if ($res) return success();
        return error();
    }
    // 上传图片
    public function uploadImg()
    {
        $file =  request()->file();
        if (!$file) {
            return error('请上传jpg,png后缀图片');
        }
        LogService::record(
            user_id: $this->uid,
            name: '上传文章图片',
            user_type: $this->role == 0 ? 2 : 3,
        );
        try {
            validate(['images' => 'fileSize:5242880|fileExt:jpg,png,jpeg'])
                ->check($file);
            if (empty($file)) return error();
            $images = \think\facade\Filesystem::disk('images')->putFile('article', $file['images']);
            if (!$images) return error('图片上传失败');
            $images = '/static/images/' . str_replace('\\', '/', $images);
            Db::name('files')->insert([
                'user_id' => $this->uid,
                'desc' => '文章图片上传',
                'route_path' => request()->controller() . '/' . request()->action(),
                'file_name' => $file['images']->getFilename(),
                'file_path' => $images,
                'size' => $file['images']->getSize(),
                'create_time' => time()
            ]);
            $json = [
                'errno' => 0,
                'data' =>  ['url' => addHost($images)]
            ];
            return json($json);
        } catch (\think\exception\ValidateException $e) {
            return error($e->getMessage());
        }
    }
}
